package cn.lblbc.lib.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import cn.lblbc.lib.R
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class LblViewPager(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
    private var viewPager: ViewPager2
    private var tabLayout: TabLayout
    private lateinit var adapter: TabPagerAdapter
    private lateinit var mOnInitFragment: (id: String) -> Fragment

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.lbl_view_vp, this, true)
        viewPager = view.findViewById(R.id.viewPager)
        tabLayout = view.findViewById(R.id.tabLayout)
    }

    fun init(fragmentActivity: FragmentActivity, tabBeanList: List<TabBean>, selectedIndex: Int, onInitFragment: (id: String) -> Fragment) {
        mOnInitFragment = onInitFragment
        adapter = TabPagerAdapter(fragmentActivity, tabBeanList)
        viewPager.adapter = adapter
        viewPager.currentItem = selectedIndex
        val tabLayoutMediator = TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = tabBeanList[position].name
        }
        tabLayoutMediator.attach()
    }

    private inner class TabPagerAdapter(fragmentActivity: FragmentActivity, var tabList: List<TabBean>) : FragmentStateAdapter(fragmentActivity) {
        override fun getItemCount(): Int {
            return tabList.size
        }

        override fun createFragment(position: Int): Fragment {
            return mOnInitFragment(tabList[position].id)
        }
    }
}

class TabBean(val id: String = "", val name: String = "")